package xyz.xuminghai.javafx_learn.concurrent;

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 2023/5/19 13:51 星期五<br/>
 * Task 简单使用
 *
 * @author xuMingHai
 */
public class TaskApp extends Application {

    private final HBox hBox = new HBox(30.0);

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void init() {
        Button button = new Button("readFile");
        TextArea textArea = new TextArea();
        textArea.setPrefSize(200.0, 100.0);
        // 设置换行
        textArea.setWrapText(true);

        button.setOnAction(event -> {
            Thread thread = new Thread(new Task<String>() {
                @Override
                protected String call() throws IOException, URISyntaxException {
                    String fileName = "task-app.txt";
                    URL url = getClass().getResource(fileName);
                    if (url == null) {
                        throw new FileNotFoundException(fileName);
                    }
                    return Files.readString(Path.of(url.toURI()));
                }

                @Override
                protected void succeeded() {
                    textArea.setText(getValue());
                }

                @Override
                protected void failed() {
                    throw new RuntimeException(getException());
                }

            });

            thread.setDaemon(true);
            thread.start();
        });

        hBox.setAlignment(Pos.CENTER);
        hBox.setFillHeight(false);
        hBox.getChildren().addAll(button, textArea);
    }

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle(getClass().getSimpleName());
        Scene scene = new Scene(hBox, 800, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}
